import os
import shutil
from PyQt5.QtWidgets import QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QFileDialog, \
    QMessageBox

from IflytekModelTool import setIflyModelDict
from LanguageTool import getCNfromDict, getCurLang
from fileOpTool import calculate_md5, add_suffix_if_exists
from VideoTool import play_mp3, play_wav
from mylog import addLog


class IflytekWidget(QWidget):
    IflyModelUnit = None
    projectName = None

    def __init__(self, projectName, IflyModelUnit, parent=None):
        super().__init__(parent)

        self.IflyModelUnit = IflyModelUnit
        self.projectName = projectName
        outlayout = QVBoxLayout()
        outwidget = QWidget()

        # 设置高度为 100，背景色为白色，整体为圆角
        outwidget.setFixedHeight(70)
        outwidget.setStyleSheet("""
                   background-color: white;
                   border-radius: 15px; /* 圆角 */
               """)

        # 创建标题和路径的标签
        self.title_label = QLabel("")
        self.setTitle()

        self.path_label = QLabel("path")
        self.setPath()

        # 创建垂直布局并添加两个标签
        vertical_layout = QVBoxLayout()
        vertical_layout.addWidget(self.title_label)
        vertical_layout.addWidget(self.path_label)

        # 为按钮设置样式
        button_style = """
                QPushButton {
                    background-color: #2E5A8B;
                    color: white; /* 字体颜色 */
                    border: none; /* 无边框 */
                    border-radius: 10px; /* 圆角 */
                    font-size: 14px; /* 字体大小 */
                    padding: 8px 16px; /* 内边距 */
                }

                QPushButton:hover {
                    background-color: blue;
                }

                QPushButton:pressed {
                    background-color: #191970; /* 按下时背景变深 */
                }
                """
        # 创建按钮
        self.import_button = QPushButton('')
        self.import_button.setMaximumWidth(100)
        self.import_button.setMinimumHeight(40)
        self.btn_import_label()
        self.play_button = QPushButton(getCNfromDict('TabBar05-btnplay'))
        self.play_button.setMaximumWidth(100)
        self.play_button.setMinimumHeight(40)
        self.export_button = QPushButton(getCNfromDict('TabBar05-btnSave'))
        self.export_button.setMaximumWidth(100)
        self.export_button.setMinimumHeight(40)
        self.restore_button = QPushButton(getCNfromDict('TabBar05-btnRestore'))
        self.restore_button.setMaximumWidth(100)
        self.restore_button.setMinimumHeight(40)

        self.import_button.setStyleSheet(button_style)
        self.play_button.setStyleSheet(button_style)
        self.export_button.setStyleSheet(button_style)
        self.restore_button.setStyleSheet(button_style)

        self.import_button.clicked.connect(self.btn_import_clicked)
        self.play_button.clicked.connect(self.btn_play_clicked)
        self.export_button.clicked.connect(self.btn_export_clicked)
        self.restore_button.clicked.connect(self.btn_restore_clicked)

        # 创建水平布局并添加垂直布局和三个按钮
        horizontal_layout = QHBoxLayout()
        horizontal_layout.addLayout(vertical_layout)  # 添加垂直布局
        horizontal_layout.addStretch()  # 添加弹性空间，使按钮靠右对齐
        horizontal_layout.addWidget(self.import_button)
        horizontal_layout.addWidget(self.play_button)
        horizontal_layout.addWidget(self.export_button)
        horizontal_layout.addWidget(self.restore_button)

        # 为主组件设置布局
        # self.setLayout(horizontal_layout)

        outwidget.setLayout(horizontal_layout)
        outlayout.addWidget(outwidget)
        self.setLayout(outlayout)

    def setTitle(self):
        self.title_label.setText(self.IflyModelUnit['content-'+str(getCurLang())])
        self.title_label.setStyleSheet("font-size: 18px; font-weight: bold; border: none;")  # 大字标题

    def setPath(self):
        if self.IflyModelUnit['curFile'] != "":
            # 有修改
            self.path_label.setText(self.IflyModelUnit['curFile'])
            self.path_label.setStyleSheet("font-size: 14px; color: red; border: none;")  # 小字路径
        else:
            # 无修改
            filePath = "./project/kedaxunfei/" + self.projectName + self.IflyModelUnit['orgFile'][1:]
            # print(filePath)
            md5 = calculate_md5(filePath)
            self.path_label.setText(self.IflyModelUnit['orgFile'])
            if md5 == self.IflyModelUnit['orgFileMD5'].upper():
                # 是原厂音频
                self.path_label.setStyleSheet("font-size: 14px; color: gray; border: none;")  # 小字路径
            else:
                # 非原厂音频，已固化到包里
                self.path_label.setStyleSheet("font-size: 14px; color: blue; border: none;")  # 小字路径

    def btn_import_clicked(self):
        """导入按钮事件"""
        addLog('IflytekWidget', 'info', f"btn_import_clicked")
        # 没修改的时候，是”导入“，有修改的是”取消“
        if self.IflyModelUnit['curFile'] == "":
            file_dialog = QFileDialog()
            file_dialog.setFileMode(QFileDialog.ExistingFile)
            file_dialog.setNameFilter("MP3 Files (*.mp3)")
            if file_dialog.exec_():
                selected_files = file_dialog.selectedFiles()
                addLog('IflytekWidget', 'info', f"Selected File: {selected_files[0]}")
                self.IflyModelUnit['curFile'] = selected_files[0]
                # 更新显示
                self.setPath()
                self.btn_import_label()
                # 更新工程整体信息文件
                setIflyModelDict(self.projectName, self.IflyModelUnit['key'], self.IflyModelUnit)
                addLog('IflytekWidget', 'info', f"import ok!")
        else:
            self.IflyModelUnit['curFile'] = ""
            self.IflyModelUnit['curFileMD5'] = ""
            # 更新显示
            self.setPath()
            self.btn_import_label()
            # 更新工程整体信息文件
            setIflyModelDict(self.projectName, self.IflyModelUnit['key'], self.IflyModelUnit)
            addLog('IflytekWidget', 'info', f"cancel import")

    def btn_import_label(self):
        if self.IflyModelUnit['curFile'] == "":
            self.import_button.setText(getCNfromDict('TabBar05-btnchange'))
        else:
            self.import_button.setText(getCNfromDict('TabBar05-btncancel'))

    def btn_play_clicked(self):
        """播放按钮事件"""
        addLog('IflytekWidget', 'info', f"btn_play_clicked")
        filePath = ""
        if self.IflyModelUnit['curFile'] == "":
            # 无修改
            filePath = "./project/kedaxunfei/" + self.projectName + self.IflyModelUnit['orgFile'][1:]
        else:
            filePath = self.IflyModelUnit['curFile']
        # print(os.path.abspath(filePath))
        addLog('IflytekWidget', 'info', f"play file: {os.path.abspath(filePath)}")
        if os.path.exists(os.path.abspath(filePath)):
            with open(os.path.abspath(filePath), "rb") as file:
                # 读取前16个字节
                first_16_bytes = file.read(16).decode('utf-8', errors='ignore')
                # print(first_16_bytes)
                if first_16_bytes[:4] == 'RIFF':
                    # print('wave')
                    addLog('IflytekWidget', 'info', f"play wave")
                    play_wav(os.path.abspath(filePath))
                else:
                    # print('mp3')
                    addLog('IflytekWidget', 'info', f"play mp3")
                    play_mp3(os.path.abspath(filePath))
        else:
            self.show_message(getCNfromDict('TabBar05-btnplayErr'), 1)
            addLog('IflytekWidget', 'warn', f"file not exists")

    def btn_export_clicked(self):
        """导出按钮事件"""
        addLog('IflytekWidget', 'info', f"btn_export_clicked")
        # 导出已固化的音频文件
        # 打开路径选择器对话框，选择存储目标路径
        target_directory = QFileDialog.getExistingDirectory(self, '选择目标文件夹', './exported')

        if target_directory:
            # 定义源文件路径和目标文件路径
            source_file = "./project/kedaxunfei/" + self.projectName + self.IflyModelUnit['orgFile'][1:]
            target_file = f'{target_directory}/({self.projectName})' + self.IflyModelUnit['orgFile'].split('/')[-1]
            # 检验是否存在同名文件，如果存在同名文件，在文件名后缀增加"(1)"
            target_file = add_suffix_if_exists(target_file)
            try:
                # 复制文件到目标路径
                shutil.copy(source_file, target_file)
                self.show_message(getCNfromDict('TabBar05-btnSaveMsgOk'), 0)
                addLog('IflytekWidget', 'info', f"export {source_file} to {target_file}, finish")
            except Exception as e:
                self.show_message(getCNfromDict('TabBar05-btnSaveMsgErr'), 1)
                addLog('IflytekWidget', 'error', f"export {source_file} to {target_file}, error")

    def btn_restore_clicked(self):
        """还原按钮事件"""
        # print(self.IflyModelUnit)
        addLog('IflytekWidget', 'info', f"btn_restore_clicked")
        if self.IflyModelUnit['curFile'] == "":
            # 无修改
            filePath = "./project/kedaxunfei/" + self.projectName + self.IflyModelUnit['orgFile'][1:]
            # print(filePath)
            md5 = calculate_md5(filePath)
            if md5 == self.IflyModelUnit['orgFileMD5'].upper():
                addLog('IflytekWidget', 'info', f"It's original factory audio")
                return

        # 有修改
        # 设置self.IflyModelUnit['curFile']为原厂包的路径
        self.IflyModelUnit['curFile'] = self.IflyModelUnit['orgPath']
        self.IflyModelUnit['curFileMD5'] = self.IflyModelUnit['orgFileMD5']
        # 更新显示
        self.setPath()
        self.btn_import_label()
        # print(self.IflyModelUnit)
        # 更新工程整体信息文件
        setIflyModelDict(self.projectName, self.IflyModelUnit['key'], self.IflyModelUnit)
        addLog('IflytekWidget', 'info', f"restore over")

    def show_message(self, message, type=0):
        """显示提示消息框"""
        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Information)
        if type == 0:
            msg_box.setWindowTitle(getCNfromDict('megboxTitle-tip'))
        else:
            msg_box.setWindowTitle(getCNfromDict('megboxTitle-err'))
        msg_box.setText(message)
        msg_box.setStandardButtons(QMessageBox.Ok)
        msg_box.exec_()

